﻿// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;

namespace System.ComponentModel.Composition
{
    internal static class CompositionContainerExtensions
    {
        public static bool IsPresent<T>(this CompositionContainer container)
        {
            try
            {
                container.GetExportedObject<T>();
                return true;
            }
            catch (CardinalityMismatchException)
            {
                return false;
            }
        }

        public static bool IsPresent(this CompositionContainer container, string contractName)
        {
            try
            {
                container.GetExportedObject<object>(contractName);
                return true;
            }
            catch (CardinalityMismatchException)
            {
                return false;
            }
        }

        public static void AddParts(this CompositionContainer container, params object[] parts)
        {
            foreach (object instance in parts)
            {
                ComposablePart part = instance as ComposablePart;
                if (part != null)
                {
                    container.AddPart(part);
                }
                else
                {
                    container.AddPart((object)instance);
                }
            }
        }
    }
}
